<?php

namespace App\Http\Controllers\Home\Set;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Home\Users as UsersModel;
use Illuminate\Support\Facades\Auth;
use Users;
use App\Models\Home\Config;
use Conf;

class MacController extends Controller
{
    protected $passField = [
        'mac','describe'
    ];

    public function mac_log(Request $request)
    {
        $mac_list = Users::getMacList();

        $mac_flag = Config::where('name','mac')->first();

        return view('Home.User.Set.Mac.mac-log',compact('mac_list','mac_flag'));
    }

    public function mac_add()
    {
        if(request()->isMethod('post')){
            //验证
            $this->validate(request(), [
                'mac' => 'required|string',
                'uid' => 'required|integer',
            ],[],[
                'mac' => 'MAC地址',
                'uid' => '用户ID',
            ]);

            $user = UsersModel::where('id',intval(request()->post('uid')))->where('status',1)->first();

            if($user){

                //数据库操作
                foreach (request()->all() as $key => $val){
                    if (!is_numeric($val)){	$val = clean($val);}
                    if(in_array($key,$this->passField) && trim($val)){
                        $user->$key = $val;
                    }
                }

                $user->mac_uid = Auth::id();

                $user->mac_time = time();

                $user->save();
                //返回结果
                return ['code'=>1];

            }else{

                return ['code'=>1,'msg'=>'用户不存在或已被删除'];

            }

        }

        $mac_list = Users::getNoMacList();

        return view('Home.User.Set.Mac.add',compact('mac_list'));
    }

    public function mac_edit(UsersModel $obj)
    {
        if(request()->isMethod('post')){
            //验证
            $this->validate(request(), [
                'mac' => 'required|string',
            ],[],[
                'mac' => 'MAC地址',
            ]);

            //数据库操作
            foreach (request()->all() as $key => $val){
                if (!is_numeric($val)){	$val = clean($val);}
                if(in_array($key,$this->passField) && trim($val)){
                    $obj[$key] = $val;
                }
            }

            $obj->mac_uid = Auth::id();

            $obj->mac_time = time();

            $obj->save();
            //返回结果
            return ['code'=>1];
        }

        return view('Home.User.Set.Mac.edit',compact('obj'));

    }

    public function mac_del(UsersModel $obj)
    {

        $obj->mac = null;

        $obj->mac_uid = Auth::id();

        $obj->mac_time = time();

        $obj->save();

        return ['code'=>1];
    }

}